//
//  NearByViewController.m
//  Project_2_weibo
//
//  Created by 林林 on 16/7/8.
//  Copyright © 2016年 lhn. All rights reserved.
//

#import "NearByViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "SinaWeibo.h"
#import "Weibo.h"
#import "WeiboAnnoation.h"
#import "WeiboAnnotationView.h"

@interface NearByViewController () <MKMapViewDelegate, SinaWeiboRequestDelegate>
{
    MKMapView *_mapView;
    BOOL _isLocation;
}
@end

@implementation NearByViewController

- (void)viewDidLoad {
    
    _isLocation = NO;
    [self createMapView];
}

- (void)createMapView {
    
    if (kSystemVersion >= 8.0) {
        CLLocationManager *locationManager = [[CLLocationManager alloc] init];
        [locationManager requestWhenInUseAuthorization];
    }
    _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_mapView];
    
    _mapView.showsUserLocation = YES;
    _mapView.delegate = self;
    
}
#pragma mark - MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    
    CLLocationCoordinate2D coordinate = userLocation.coordinate;
    double lat = coordinate.latitude;  //纬度
    double lon = coordinate.longitude; //经度
    
    //范围
    MKCoordinateSpan span = MKCoordinateSpanMake(0.03, 0.03);
    
    //显示区域
    MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, span);
    [_mapView setRegion:region animated:YES];
    
    if (_isLocation == NO) {
        _isLocation = YES;
        SinaWeibo *weibo = kWeiboObject;
        //参数
        NSDictionary *dic = @{@"long" : [NSString stringWithFormat:@"%f", lon], @"lat" : [NSString stringWithFormat:@"%f", lat]};
        [weibo requestWithURL:@"place/nearby_timeline.json" params:[dic mutableCopy] httpMethod:@"GET" delegate:self];
    }
    
}

#pragma mark - SinaWeiboRequestDelegate
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    
    NSArray *status = result[@"statuses"];
    for (NSDictionary *dic in status) {
        Weibo *wb = [Weibo yy_modelWithDictionary:dic];
        WeiboAnnoation *annoation = [[WeiboAnnoation alloc] init];
        annoation.weibo = wb;
        //在地图中添加标注
        [_mapView addAnnotation:annoation];
    }
    
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    
    WeiboAnnotationView *annotationView = (WeiboAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:@"WeiboAnnotationView"];
    if (annotationView == nil) {
        annotationView = [[WeiboAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"WeiboAnnotationView"];
    }
    return annotationView;
    
}

@end





